package com.njupt.user.impl;

import java.util.List;

import com.njupt.impl.GenericPaginationManagerImpl;
import com.njupt.user.model.User;
import com.njupt.auth.service.UserManager;
import com.njupt.system.model.UserAuthority;
import com.njupt.service.GenericPaginationManager;
import com.njupt.auth.model.UserDetails;

public class UserManagerImpl extends GenericPaginationManagerImpl<User, Long> implements UserManager
{
	private GenericPaginationManager<UserAuthority, Long> userAuthorityManager;
	public UserManagerImpl(Class<User> entityClass) {
		super(entityClass);
	}
	public User getUserByUsername(String username) {
		User u = this.findUniqueBy("username", username);
		return u;
	}
	@SuppressWarnings("unchecked")
	public UserDetails loadUserByUsername(String username) {
		User user = getUserByUsername(username);
		if(user == null)return null;
		// TODO 应该写在UserManager里更为合适些。
		String hql = "from UserAuthority where username=?";
		List<UserAuthority> userAuthorities = userAuthorityManager.findByHql(hql, new Object[]{username});
		String[] authorities = new String[userAuthorities.size()];
		int j = 0;
		for (UserAuthority userAuthority : userAuthorities) {
			authorities[j++] = userAuthority.getAuthority();
		}
		user.setAuthorities(authorities);
		return user;
	}
	@SuppressWarnings("unchecked")
	@Override
	public List<UserDetails> getAllUsers()
	{
		return this.find("from User");
	}
	public GenericPaginationManager<UserAuthority, Long> getUserAuthorityManager()
	{
		return userAuthorityManager;
	}
	public void setUserAuthorityManager(GenericPaginationManager<UserAuthority, Long> userAuthorityManager)
	{
		this.userAuthorityManager = userAuthorityManager;
	}
}
